let app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentType: 'done',
    url: '',
    userId: 0,
    finishRecord: [],
    noFinishRecord: [],
    pageNum: 1,
    pageSize: 6,
    isLoading: false,
    hasMoreData: true
  },
  // 跳转到评价页面
toevaluate(e) {
  // 获取当前点击项的索引
  const index = e.currentTarget.dataset.index;
  // 根据当前类型获取对应的记录数组
  const currentRecords = this.data.currentType === 'done' ? this.data.finishRecord : this.data.noFinishRecord;
  // 获取当前记录项
  const currentItem = currentRecords[index];
  
  if (!currentItem || !currentItem.consultantId) {
    wx.showToast({
      title: '获取咨询师信息失败',
      icon: 'none'
    });
    return;
  }
  
  // 跳转到评价页面并传递consultantId
  wx.navigateTo({
    url: `/pages/consult/consultDetails/review/review?consultantId=${currentItem.consultantId}&myConsultId=${currentItem.id}`,
   
  });
  console.log(currentItem.consultantId)
  console.log(currentItem.id)
},
  changeType(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      currentType: type,
      pageNum: 1, // 切换类型时重置页码
      finishRecord: [], // 清空当前类型数据
      noFinishRecord: [],
      hasMoreData: true
    }, () => {
      this.getMyConsult(); // 切换后重新加载数据
    });
  },

  // 取消预约方法
  cancelAppointment(e) {
    const recordId = e.currentTarget.dataset.id;
    if (!recordId) {
      wx.showToast({
        title: '获取记录ID失败',
        icon: 'none'
      });
      return;
    }
    
    // 显示确认对话框
    wx.showModal({
      title: '取消预约',
      content: '确定要取消此次预约吗？',
      success: (res) => {
        if (res.confirm) {
          // 用户确认取消，调用接口
          wx.request({
            url: this.data.url + 'myConsult/' + recordId,
            method: "DELETE",
            success: (resp) => {
              if (resp.statusCode === 200) {
                wx.showToast({
                  title: '取消预约成功',
                  icon: 'success'
                });
                // 重置当前类型数据并重新加载
                this.setData({
                  pageNum: 1,
                  finishRecord: [],
                  noFinishRecord: [],
                  hasMoreData: true
                }, () => {
                  this.getMyConsult();
                });
              } else {
                wx.showToast({
                  title: `取消失败（状态码：${resp.statusCode}）`,
                  icon: 'none'
                });
              }
            },
            fail: (err) => {
              console.error('取消预约请求失败', err);
              wx.showToast({
                title: '网络错误，取消失败',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  },

  getMyConsult() {
    if (!this.data.userId || this.data.isLoading || !this.data.hasMoreData) return;

    this.setData({ isLoading: true });
    wx.showLoading({ title: "加载中..." });

    // 根据当前类型确定要传递的status值
    const status = this.data.currentType === 'done' ? '已完成' : '未完成';

    wx.request({
      url: this.data.url + 'myConsult/getPages',
      method: "GET",
      data: {
        userId: this.data.userId,
        pageNum: this.data.pageNum,
        pageSize: this.data.pageSize,
        status: status // 传递状态参数
      },
      success: (resp) => {
        console.log('接口响应:', resp.data);
        const respData = resp.data.data || {};
        const records = respData.list || [];

        // 处理结束时间
        const processedRecords = records.map(item => {
          if (item.consultTime) { 
            const startTime = new Date(item.consultTime).getTime();
            const endTimeStamp = startTime + 7 * 24 * 60 * 60 * 1000;
            const endDate = new Date(endTimeStamp);
            const year = endDate.getFullYear();
            const month = String(endDate.getMonth() + 1).padStart(2, '0');
            const day = String(endDate.getDate()).padStart(2, '0');
            item.eTime = `${year}-${month}-${day}`;
          }
          return item;
        });

        // 根据当前类型添加到对应数组
        if (this.data.currentType === 'done') {
          this.setData({
            finishRecord: [...this.data.finishRecord, ...processedRecords]
          });
        } else {
          this.setData({
            noFinishRecord: [...this.data.noFinishRecord, ...processedRecords]
          });
        }

        // 判断是否还有更多数据
        const totalPages = respData.pages || 0;
        this.setData({
          hasMoreData: this.data.pageNum < totalPages
        });
      },
      fail: (err) => {
        console.error('获取咨询记录失败', err);
        wx.showToast({
          title: '获取数据失败',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
        this.setData({ isLoading: false });
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      url: app.globalData.url
    });
    const userInfo = wx.getStorageSync('user');
    if (userInfo && userInfo.id) {
      this.setData({
        userId: userInfo.id
      }, () => {
        this.getMyConsult();
      });
    } else {
      console.warn('未获取到用户信息');
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const userInfo = wx.getStorageSync('user');
    if (userInfo && userInfo.id && userInfo.id !== this.data.userId) {
      this.setData({
        userId: userInfo.id,
        pageNum: 1,
        finishRecord: [],
        noFinishRecord: [],
        hasMoreData: true
      }, () => {
        this.getMyConsult();
      });
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      pageNum: 1,
      finishRecord: [],
      noFinishRecord: [],
      hasMoreData: true
    }, () => {
      this.getMyConsult();
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.hasMoreData && !this.data.isLoading) {
      this.setData({
        pageNum: this.data.pageNum + 1
      }, () => {
        this.getMyConsult();
      });
    } else if (!this.data.hasMoreData) {
      wx.showToast({
        title: '没有更多数据了',
        icon: 'none'
      });
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
    